<?php
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
/**
 * @Author:    dx
 * @DateTime:  2017-08-02 13:31:17
 * @Description: 套餐卡
 */
class ServiceCardController extends BaseController
{
    /**
     * @Author:      dx
     * @DateTime:  2017-08-02 13:31:17
     * @Description: 套餐卡 下单 订单
     */
    public function create(){
        $validator = Validator::make(Input::all(),
            array(
                'token'  => 'required',
                'shop_id'  => 'required',
                'service_card_base_id'  => 'required',
                'order_source' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }
            $service_card_base_id = Input::get('service_card_base_id');
            $car_no = strtoupper(Input::get('car_no'));
            $scb=ServiceCardBase::find($service_card_base_id);
            if(is_null($scb)||$scb->sale_status==0){
                $response = Lang::get("error.service_card_status_error_95003");
                break;
            }
            if($scb->sale_limit==1&&(strtotime($scb->sale_begin_date)>time()||strtotime($scb->sale_end_date)<time())){
                $response = Lang::get("error.service_card_time_error_95004");
                break;
            }
            $scbs=ServiceCardBaseShop::where("service_card_base_id",$scb->id)->where("shop_id",Input::get('shop_id'))->where("status",1)->first();//判断是否支持该门店
            if(is_null($scbs)){
                $response = Lang::get("error.service_card_status_error_95003");
                break;
            }
            if($scb->limit_car==1&&empty($car_no)){//如果限制领卡车俩没传车辆则不能使用
                $response = Lang::get("error.service_card_car_error_95005");
                break;
            }

            $sco=new ServiceCardOrder();
            $order_id = Common::createOrderId();
            $sco->order_id = $order_id;
            $sco->status =1011;
            $sco->car_no = $car_no?$car_no:"";
//            $sco->pay_type = Input::get('pay_type');
            $sco->amount = $scb->amount;
            $sco->service_card_detail_id = '';
            $sco->service_card_id = $scb->id;
            $sco->shop_id = Input::get('shop_id');
            $sco->user_id=$wx_user->id;
            $sco->create_by = $wx_user->id;
            $sco->order_source = Input::get('order_source');
            $sco->save();

            $sc_order_flows = new ServiceCardOrderFlow;
            $sc_order_flows->order_id = $order_id;
            $sc_order_flows->status =1011;
            $sc_order_flows->user_id = $wx_user->id;
            $sc_order_flows->type = 'custom';
            $sc_order_flows->save();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("order_id"=>$order_id));

        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "/service_card/create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:  2017-08-03 10:01:17
     * @Description: 套餐卡 卡包列表
     */
    public function card_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token'  => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }
            $service_card_list = array();
            $sc = ServiceCardDetail::where('status',2)->where('user_id',$wx_user->id)->orderBy('get_time','desc')->get();
            if(!is_null($sc)){
                foreach($sc as $_s){
                    $scb = ServiceCardBase::where('id',$_s->service_card_base_id)->first();
                    if(!is_null($scb)){
                        if($scb->date_type == 1){
                            $begin_date = $_s->get_time;
                            $end_date = $_s->end_date;
                        }else{
                            $begin_date = $scb->begin_date;
                            $end_date = $scb->end_date;
                        }
                        $status_value = '';
                        if(strtotime($end_date) < time()){
                            $status_value = '已过期';
                        }
                        $sco = ServiceCardOrder::where('user_id',$wx_user->id)->where('service_card_detail_id',$_s->id)->where('service_card_id',$scb->id)->first();
                        $shop_value = [];
                        if($scb->limit_shop == 1){
                            $shop_value = ServiceCardDetail::leftjoin('maintenance_shops as ms','service_card_detail.shop_id','=','ms.id')
                                ->where('service_card_detail.user_id',$wx_user->id)->where('service_card_detail.id',$_s->id)->select('ms.name')->get()->toArray();
                        }else{
                            $shop_value = ServiceCardBaseShop::leftjoin('maintenance_shops as ms','service_card_base_shop.shop_id','=','ms.id')
                                ->where('service_card_base_shop.service_card_base_id',$scb->id)->where('service_card_base_shop.status',1)->select('ms.name')->get()->toArray();
                        }
                        $scdp = ServiceCardDetailPack::where('service_card_detail_id',$_s->id)->where('service_card_base_id',$scb->id)->select('curr_number')->get();
                        $i = 0;
                        foreach($scdp as $v){
                            $i += $v->curr_number;
                        }
                        $_service_card = array();
                        $_service_card["id"] = $scb->id;
                        $_service_card["card_no"] = $_s->id;
                        $_service_card["name"] = $scb->name;
                        $_service_card["limit_car"] = $scb->limit_car;
                        $_service_card["limit_shop"] = $scb->limit_shop;
                        $_service_card['begin_date'] = date('Y-m-d',strtotime($begin_date));
                        $_service_card['end_date'] = date('Y-m-d',strtotime($end_date));
                        $_service_card['status_value'] = $status_value;
                        $_service_card['car_no'] = isset($sco->car_no)?$sco->car_no:"";
                        $_service_card['shop_value'] = $shop_value;
                        $_service_card['curr_number'] = $i;
                        array_push($service_card_list, $_service_card);

                    }
                }
            }
            $if_have_account_no = ServiceCardCar::where('user_id',$wx_user->id)->where('status',1)->count();
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("service_card_list"=>$service_card_list,'if_have_account_no'=>$if_have_account_no));
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "/service_card/card_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:  2017-08-03 17:16:56
     * @Description: 获取当前可售卖的套餐卡信息
     */
    public function sale_card_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token'=> 'required',
                'city'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }
            $city_change = ResourceCityType::getCity(Input::get('city'));
            if(is_null($city_change)){
                $city_id = 1;
            }else{
                $city_id = $city_change->id;
            }

            $scb=ServiceCardBase::leftjoin('service_card_base_city as c','service_card_base.id','=','c.service_card_base_id')->where("service_card_base.sale_status",1)->where('c.city_id',$city_id)->where('c.status',1)->where('service_card_base.user_status',1)->where('service_card_base.sale_limit', 0)->where(function($query)
            {
                $query->where('service_card_base.c_sale', 1)
                    ->orWhere(function($query1)
                    {
                        $query1->where('service_card_base.sale_begin_date',"<",Common::currentTimeString())
                            ->Where('service_card_base.sale_end_date',">",Common::currentTimeString());
                    });
            })->select('service_card_base.id','service_card_base.name','service_card_base.amount','service_card_base.limit_car','service_card_base.limit_shop','service_card_base.begin_date','service_card_base.end_date','service_card_base.buy_number')->get()->toArray();
            $sale_card_list = array();
            if(!is_null($scb)){
                foreach($scb as $v){
                    //判断当前用户是不是已经超过了最大购买限制   0是不限制
                    if($v['buy_number'] > 0){
                        $buy_number = ServiceCardOrder::where("user_id",$wx_user->id)->where('service_card_id',$v['id'])->where('status',1417)
                            ->count();
                        if ($v['buy_number'] <=  $buy_number){
                            continue;
                        }
                    }
                    $scbp = ServiceCardBasePack::leftjoin('product_package as pp','service_card_base_pack.pack_id','=','pp.id')
                        ->where('service_card_base_pack.service_card_base_id',$v['id'])
                        ->select('service_card_base_pack.number','service_card_base_pack.amount','pp.name')->get()->toArray();
                    $v['product_pack'] = $scbp;
                    $sale_card_list[] = $v;
                }
            }
            $temp_arr=array("count"=>sizeof($sale_card_list),"sale_card_list"=>$sale_card_list);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "/service_card/sale_card_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:  2017-08-07 13:55:29
     * @Description: 套餐卡 详细信息
     */
    public function show(){
        $validator = Validator::make(Input::all(),
            array(
                'token'=> 'required',
                'id'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }
            $scb=ServiceCardBase::where("id",Input::get("id"))->first();
            if(is_null($scb)){
                $response = Lang::get("error.service_card_base_error_95000");
                break;
            }
            //获取服务信息
            $scbp=ServiceCardBasePack::leftJoin("product_package","product_package.id","=","service_card_base_pack.pack_id")->where("service_card_base_pack.service_card_base_id",$scb->id)->select("service_card_base_pack.*","product_package.name")->get();
            $scbs=ServiceCardBaseShop::leftjoin("maintenance_shops as ms",'ms.id','=','service_card_base_shop.shop_id')->where('service_card_base_shop.service_card_base_id',$scb->id)->where('service_card_base_shop.status',1)->select('ms.id','ms.name')->get();

            $temp_arr=array("service_card_base"=>$scb,"service_card_base_pack"=>$scbp,"service_card_base_shop"=>$scbs);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "/service_card/show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:  2017-08-07 15:55:29
     * @Description: 校验身份证
     */
    public function check_card(){
        $validator = Validator::make(Input::all(),
            array(
                'token'=> 'required',
                'card_no'=> 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }

            if($wx_user->id_card==""){
                $response = Lang::get("error.service_card_user_num_error_95001");
                break;
            }
            if(substr($wx_user->id_card,-4) != Input::get('card_no')){
                $response = Lang::get("error.service_card_user_num_error_95002");
                break;
            }

            $response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "/service_card/check_card", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:  2017-08-11 15:12:40
     * @Description: 套餐卡的支付
     */
    public function order_pay(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'pay_type' => 'required',
                'amount' => 'required',
                'trade_type' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }
            $order_id=Input::get("order_id");

            $order=ServiceCardOrder::find($order_id);
            if(is_null($order)){
                $response = Lang::get("error.service_card_order_error_95009");
                break;
            }
            if($order->status!=1011){
                $response = Lang::get("error.service_card_wx_pay_error_95006");
                break;
            }

            if(!in_array(Input::get('pay_type'),array(3,8))){
                $response = Lang::get("error.service_card_pay_type_error_95010");
                break;
            }

            $wx_response = ServiceCardOrderPayRecord::order_pay($order_id,Input::get("pay_type"),Input::get("amount"),$wx_user->id,"custom",0,3);
            Log::info('service_card_wx_pay',array('function' => 'order_pay','response'=> $wx_response));

            if($wx_response['code'] == 0 && isset($wx_response['result']['wx_record_id'])){
                $order=ServiceCardOrder::find($order_id);

                $wp=WeixinRecord::where("id",$wx_response['result']['wx_record_id'])->first();
                if(is_null($wp)){
                    $response = Lang::get("error.service_card_wx_pay_record_error_95012");
                    break;
                }

                $wx = Config::get('wechat.CHEPIN');
                $options = $wx['OPTION'];
                $app = new Application($options);
                $payment = $app->payment;
                $attributes = [
                    'trade_type'       => Input::get('trade_type'), // JSAPI，NATIVE，APP...
                    'body'             => '套餐卡订单支付'.$order_id,
                    'detail'           => '套餐卡订单支付',
                    'out_trade_no'     => 'service_card-'.$wx_response['result']['wx_record_id'],
                    'total_fee'        => 1,//$amount, // 单位：分  测试1分
                    'product_id'       => 'service_card_pay',
                    'notify_url'       => Config::get('wechat.pay_note_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                    'openid'           => $wx_user->openid, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                ];
                $weixin_order = new Order($attributes);
                $result = $payment->prepare($weixin_order);
                Log::info('service_card_wx_pay',array('function' => 'order_pay','response'=> $result));
                if ($result->return_code == 'SUCCESS'&&$result->result_code == 'SUCCESS'){
                    $prepayId = $result->prepay_id;
                    $config = $payment->configForJSSDKPayment($prepayId); // 这个方法是取得js里支付所必须的参数用的
                    $wp->wx_pay_id=$result->prepay_id;
                    $wp->status=0;
                    $response = array('code' => 0, 'msg' => 'ok', 'result' => array('config'=>$config));
                }else{
                    $wp->status=2;
                }
                $wp->out_trade_no='service_card-'.$wx_response['result']['wx_record_id'];
                $wp->order_id=$order_id;
                $wp->amount=Input::get('amount');
                $wp->save();
            }
            Coupons::InvitationCoupon($wx_user->id);
        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "order_pay", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:  2017-08-16 12:06:16
     * @Description: 创建h5 微信支付
     */
    public function unified_order(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'order_id' => 'required',
                'pay_type' => 'required',
                'amount' => 'required',//单位元
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $wx_user=$this->verificationUserToken(Input::get("token"),$response);
            if(is_null($wx_user)){
                break;
            }
            $order_id=Input::get("order_id");
            $pay_type=Input::get("pay_type");
            $pay_amount=Input::get("amount");
            $trade_type=Input::get("trade_type");

            if(!in_array(Input::get('pay_type'),array(3,8))){
                $response = Lang::get("error.service_card_pay_type_error_95010");
                break;
            }
            $response=DB::transaction(function () use ($order_id,$pay_type,$wx_user,$pay_amount,$trade_type) {
                $mweb_url = "";
                $order = ServiceCardOrder::where("order_id",$order_id)->lockForUpdate()->first();
                if(in_array($order->status,array(1117,1217,1417))){//是否已结算
                    DB::rollback();
                    $response = Lang::get("scs_error.order_status_error_40040");
                    return $response;
                }
                $temp_pay=ServiceCardOrderPayRecord::where("order_id",$order->order_id)->where("status",1)->where("pay_type",$pay_type)->first();
                if($temp_pay){
                    DB::rollback();
                    $response = Lang::get("scs_error.order_pay_record_40131");
                    return $response;
                }
                $order_amount=$pay_amount*100;
                $temp_amount=ServiceCardOrderPayRecord::where("order_id",$order->order_id)->whereIn("status",array(0,5))->sum("amount");
                if(bcsub($order->amount, $order->pay_amount,0)<($order_amount+$temp_amount)){
                    DB::rollback();
                    $response = Lang::get("scs_error.order_pay_record_40113");
                    return $response;
                }
                $tran_no = date('YmdHis',time()).Common::generateCode(8);
                if($wx_user->id == 1000000000 && $pay_type == 8){//特殊账户不能余额
                    DB::rollback();
                    $response = Lang::get("scs_error.order_user_notpay_40059");
                    return $response;
                }
                if($pay_type == 3 && empty($trade_type)){//微信支付
                    DB::rollback();
                    $response = Lang::get("error.service_card_trade_type_empty_error_95015");
                    return $response;
                }
                //验证完成订单支付
                $o_p=new ServiceCardOrderPayRecord;
                $o_p->user_id=$wx_user->id;
                $o_p->order_id=$order_id;
                $o_p->pay_type=$pay_type;
                $o_p->amount=$order_amount;
                $o_p->status=1;//默认正常 后面根据实际情况更改状态
                $o_p->create_by=$wx_user->id;
                $o_p->tran_no=$tran_no;
                $o_p->create_type='custom';
                $o_p->implement_time=Common::currentTimeString();
                $o_p->save();
                switch ($pay_type) {
                    case 8://个人余额 暂时不判断 因为个人 余额现在都为空 新版本判断用户余额
                        $user_balance=UserAccountDeatails::where("user_id",$wx_user->id)->whereIn("acount_type",array(1,2))->sum("balance");
                        if(($user_balance) >= $order_amount){
                            $arr=AcountUserRecharge::getUseRecharge($order->shop_id,$wx_user->id,$order_amount,2,"asc");
                            if(sizeof($arr)>0){
                                foreach ($arr as $_arr) {
                                    //记录了用户的充值消费记录
                                    $aurs=new AcountUserRechargeSpend;
                                    $aurs->aurr_id=$_arr->id;
                                    $aurs->user_id=$order->user_id;
                                    $aurs->buss_id=$o_p->id;
                                    $aurs->type=8;//套餐卡订单消费
                                    $aurs->amount=$_arr->user_amount;
                                    $aurs->status=1;
                                    $aurs->tran_no=$tran_no;
                                    $aurs->shop_id=$order->shop_id;
                                    $aurs->implement_time=date("Y-m-d H:i:s",time());
                                    $aurs->save();
                                    //更改充值记录消费的记录
                                    AcountUserRecharge::where('id',$_arr->id)->update(array('current_amount'=> $_arr->current_amount -$_arr->user_amount,));
                                    //记录个人 各种账户余额
                                    Account::record($wx_user->id,$_arr->shop_id,$_arr->acount_type,$tran_no,2,223,$_arr->user_amount,'套餐卡订单结算支出,订单号:'.$order->order_id);
                                    //记录公司账户收入
                                    $base_acount_num=$_arr->acount_type==1?1:3;//如果用的现金账户 计入企业现金帐 如果是虚拟充值记录
                                    Account::record_base($base_acount_num,$tran_no,1,123,$_arr->user_amount,'套餐卡订单结算收入,订单号:'.$order->order_id);
                                }
                                ServiceCardOrderAccount::insert(array('order_id' => $order->order_id,'tran_no' => $tran_no,));
                                // app 微站下单 生成相关套餐卡信息
                                if(in_array($order->order_source,array(2,10))){
                                    ServiceCardDetailPack::createServiceCardDetail($order->order_id);
                                }
                            }else{
                                DB::rollback();
                                $response = Lang::get("scs_error.order_user_notpay_40039");
                                return $response;
                            }
                        }else{
                            DB::rollback();
                            $response = Lang::get("scs_error.order_user_notpay_40039");
                            return $response;
                        }
                        break;
                    case 3://微信支付
                        $id=Common::createOrderId();
                        $wr=new WeixinRecord;
                        $wr->id=$id;
                        $wr->order_id=$order_id;
                        $wr->amount=$order_amount;
                        $wr->user_id=$wx_user->id;
                        $wr->shop_id=$order->shop_id;
                        $wr->create_by=$wx_user->id;
                        $wr->buss_id=$o_p->id;
                        $wr->type=5;
                        $wr->save();

                        $wx = Config::get('wechat.CHEPIN');
                        $options = $wx['OPTION'];
                        $app = new Application($options);
                        $payment = $app->payment;
                        $attributes = [
                            'trade_type'       => 'MWEB', // JSAPI，NATIVE，APP...
                            'body'             => '套餐卡订单支付',
                            'detail'           => '套餐卡订单支付',
                            'out_trade_no'     => 'service_card-'.$id,
                            'total_fee'        => 1,//$pay_amount, // 单位：分
                            'product_id'       => 'service_card_pay',
                            'notify_url'       => Config::get('wechat.pay_note_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                            'spbill_create_ip'=> Common::get_client_ip(),
                        ];
                        $weixin_order = new Order($attributes);
                        $result = $payment->prepare($weixin_order);
                        Log::info('service_card_wx_pay',array('function' => 'unified_order','response'=> $result));
                        $temp_wx_record = WeixinRecord::find($id);
                        if ($result->return_code == 'SUCCESS'&&$result->result_code == 'SUCCESS'){
                            $wr->wx_pay_id=$result->prepay_id;
                            $wr->status=0;
                            $wr->save();
                            ServiceCardOrderPayRecord::where("id",$o_p->id)->update(array("status"=>5,"sources"=>1,"implement_time"=>null,"tran_no"=>''));
                        }else{
                            $wr->status=2;
                            $wr->save();
                            ServiceCardOrderPayRecord::where("id",$o_p->id)->update(array("status"=>2,"sources"=>1,"implement_time"=>null,"tran_no"=>''));
                        }
                        $temp_wx_record->out_trade_no='service_card-'.$id;
                        $temp_wx_record->save();
                        $mweb_url = $result->mweb_url;
                        $order_amount=0;//修改支付金额为0 回调产生才算是支付完成
                        break;
                    default:
                        # code...
                        break;
                }
                $op_arr=ServiceCardOrderPayRecord::where("order_id",$order->order_id)->whereIn("status",array(0,1,5))->get();
                $order->pay_amount=$order->pay_amount+$order_amount;
                $order->pay_type=sizeof($op_arr)==1?$pay_type:9;
                $order->save();

                $temp_arr =  array('order_id'=>$order_id,'mweb_url'=>$mweb_url);
                return $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
            });

        }while(false);
        Log::info("info", array("system" => "wechat2.0" ,"event" => "unified_order", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


}
